package org.adit.spring.hibernate.dao;

import java.util.List;

import org.adit.spring.hibernate.entity.Recurso;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;

@Component
public class RecursoDao {

	private final Session session;

	public RecursoDao(Session session) {
		this.session = session;
	}

	public void salva(Recurso recurso) {
		Transaction tx = session.beginTransaction();
		session.save(recurso);
		tx.commit();
	}

	@SuppressWarnings("unchecked")
	public List<Recurso> listaTudo() {
		return this.session.createCriteria(Recurso.class).list();
	}

	public Recurso carrega(Long id) {
		return (Recurso) this.session.load(Recurso.class, id);
	}

	public void atualiza(Recurso recurso) {
		Transaction tx = session.beginTransaction();
		session.update(recurso);
		tx.commit();
	}

	public void remove(Recurso recurso) {
		Transaction tx = session.beginTransaction();
		this.session.delete(recurso);
		tx.commit();
	}

	@SuppressWarnings("unchecked")
	public List<Recurso> buscarRecursoPorIdBusca(Long idBusca) {
		return session.createCriteria(Recurso.class).add(Restrictions.ilike("route_fk", idBusca.toString(), MatchMode.ANYWHERE)).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Recurso> busca(String tipo) {
		return session.createCriteria(Recurso.class).add(Restrictions.ilike("tipo", tipo, MatchMode.ANYWHERE)).list();
	}

	public void recarrega(Recurso recurso) {
		session.refresh(recurso);
	}
}